package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @version 1.0
 * @Author 杨旭康
 * @Date 2022/10/31 10:12
 * @question: 全局异常捕获器
 */

//无需写捕获哪种/哪层的异常 默认控制层
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //SQLIntegrityConstraintViolationException
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){

        log.info("捕获到异常: {}" + ex.getMessage());

        //获取异常信息 例如:Duplicate entry 'zhangsan' for key 'idx_username'
        //关键字 Duplicate entry 重复了直接去查此就可
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String s = split[2];
            return R.error(s + "已存在,请重新输入用户名~");
        }
        //到这里之后就是报的别的异常 发邮件给开发人员等
        return R.error("未知异常信息");
    }


    //RuntimeException
    @ExceptionHandler(RuntimeException.class)
    public R<String> exceptionHandler(RuntimeException ex){

        log.info("捕获到异常: {}" + ex.getMessage());
        //这里直接抛出 类中已定义好
        return R.error(ex.getMessage());
    }





}
